import { useClickAway } from 'ahooks'
import { Badge, Button } from 'antd'
import Avatar from 'antd/lib/avatar/avatar'
import React, { useRef, useState } from 'react'
import { connect } from 'react-redux'
import { Link, useHistory, useLocation } from 'react-router-dom'
import { E_ROUTE_PATH } from '../../router/route-path'
import { IAuthAction, setIsLoggedIn, setToken, setUserId } from '../../store/modules/auth'
import { IUserAction, setUserInfo } from '../../store/modules/user'
import { IGlobalState } from '../../store/store-types'
import './AppHeader.less'

interface IAppHeaderProps {
  hasLoginBtn?: boolean
  hasMessage?: boolean
  hasAvatar?: boolean
  hasBuyBtn?: boolean
}

type IStateProps = ReturnType<typeof mapState>

type IAppHeaderAllProps = IAppHeaderProps & IStateProps & Partial<IAuthAction> & Partial<IUserAction>

function AppHeader(props: IAppHeaderAllProps) {
  const history = useHistory()
  const location = useLocation()
  const [isMenuVisible, setIsMenuVisible] = useState(false)
  const avatarRef = useRef<HTMLDivElement>(null)
  const menuRef = useRef(null)

  function goToHome() {
    if (location.pathname === E_ROUTE_PATH.HOME) {
      return
    }
    props.setIsLoggedIn && props.setIsLoggedIn(false)
    history.push(E_ROUTE_PATH.HOME)
  }

  function goToMessageList() {
    if (location.pathname === E_ROUTE_PATH.MESSAGE_LIST) {
      return
    }
    history.push(E_ROUTE_PATH.MESSAGE_LIST)
  }

  function onProfileMenuClicked() {
    setIsMenuVisible(false)

    if (location.pathname === E_ROUTE_PATH.PROFILE) {
      return
    }
    history.push(E_ROUTE_PATH.PROFILE)
  }

  function onLogoutMenuClicked() {
    props.setIsLoggedIn && props.setIsLoggedIn(false)
    props.setUserInfo && props.setUserInfo(undefined)
    props.setToken && props.setToken('')
    props.setUserId && props.setUserId(0)

    setIsMenuVisible(false)
    history.push(E_ROUTE_PATH.HOME)
  }

  function isHomeRoute() {
    return location.pathname !== E_ROUTE_PATH.HOME
  }

  useClickAway(
    e => {
      if (avatarRef.current?.contains(e.target as Node)) {
        return
      }

      setIsMenuVisible(false)
    },
    [menuRef]
  )

  return (
    <div className="app-header">
      <div className="app-logo" onClick={goToHome} />
      <div className="app-header-right">
        {!props.isLoggedIn && !isHomeRoute() && (
          <Link to={E_ROUTE_PATH.LOGIN} className="login-btn">
            <Button type="default" shape="round">
              登录
            </Button>
          </Link>
        )}
        {props.isLoggedIn && (
          <>
            <Button className="btn-buy" type="default" shape="round">
              立即购买
            </Button>
            <Badge count={3} className="badge-msg" offset={[-2, 3]}>
              <div className="icon-badge" onClick={goToMessageList} />
            </Badge>
            <div className="avatar" onClick={() => setIsMenuVisible(true)} ref={avatarRef}>
              <Avatar size={40} src="" />
            </div>
          </>
        )}
      </div>
      {isMenuVisible && (
        <div className="setting-menu-node" ref={menuRef}>
          <div className="menu-profile menu-item" onClick={onProfileMenuClicked}>
            个人中心
          </div>
          <div className="menu-logout  menu-item" onClick={onLogoutMenuClicked}>
            退出登录
          </div>
        </div>
      )}
    </div>
  )
}

const mapState = (state: IGlobalState) => {
  return {
    isLoggedIn: state.auth.isLoggedIn
  }
}

const mapAction = {
  setIsLoggedIn,
  setToken: setToken,
  setUserId: setUserId,
  setUserInfo
}

export default connect(mapState, mapAction)(AppHeader)
